package com.runchamp;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/* This Diallog activity is in charge of handling inviting users to a certain race. Uses auto-complete in order to remember past entries.*/
public class InviteFriends extends Activity {
    private AutoCompleteTextView nameTxt;
    private String nickName;
    private AsyncHttpClient client;
    private RequestParams params;
    private String SERVER_URL = "http://runtobo.appspot.com/invitefriend/checkexcist";
    private ArrayList<String> pastInvites = null;
    private Set<String> pastSet = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invite_friends);
        nameTxt = (AutoCompleteTextView) findViewById(R.id.nameText);
        nameTxt.setHint("Enter nickname...");
        retrievePastInvites();
        updateTextView();
    }

    private void retrievePastInvites() {
        SharedPreferences prefs = getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
        pastSet = prefs.getStringSet("pastInvites", null);
        if (pastSet != null) {
            pastInvites = new ArrayList<String>(pastSet);
            Collections.sort(pastInvites);
        } else {
            pastSet = new HashSet<String>();
            pastInvites = new ArrayList<String>(pastSet);
        }
    }

    private void updateTextView() {
        ArrayAdapter adapter = new ArrayAdapter
                (this, android.R.layout.simple_list_item_1, pastInvites);
        nameTxt.setAdapter(adapter);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_invite_friends, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void addButton(View v) {
        nickName = nameTxt.getText().toString();
        nameTxt.setText("");
        nameTxt.setHint("Enter nickname...");
        boolean userExcist = checkUserExcist(nickName);

    }

    private boolean checkUserExcist(final String nickName) {
        client = new AsyncHttpClient();
        params = new RequestParams();
        params.put("userName", nickName);
        Bundle race = getIntent().getExtras();
        params.put("Key", race.get("Key"));
        params.put("Key", race.get("Key"));
        SharedPreferences prefs = getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
        params.put("inviteNickName", prefs.getString("nickname", "Someone"));

        client.post(SERVER_URL, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(JSONObject response) {
                if (response.optString("userID").equals("")) {
                    Toast.makeText(getApplicationContext(), "Error! no such nickname " + nickName, Toast.LENGTH_LONG).show();
                } else {
                    //////////////invite the friend with the userID given
                    Toast.makeText(getApplicationContext(), "Invitation sent to " + nickName, Toast.LENGTH_LONG).show();
                    if (pastSet != null) {
                        if (pastSet.size() < 30) {
                            if (!pastSet.contains(nickName)) {
                                pastSet.add(nickName);
                                pastInvites.add(nickName);
                            }
                        } else {
                            if (!pastSet.contains(nickName)) {
                                for (String s : pastSet) {
                                    pastSet.remove(s);
                                    break;
                                }
                                pastSet.add(nickName);
                                pastInvites = new ArrayList<String>(pastSet);
                            }
                        }

                        updateTextView();
                    }

                }
            }
        });


        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        SharedPreferences prefs = getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
        SharedPreferences.Editor prefEditor = prefs.edit();
        prefEditor.putStringSet("pastInvites", pastSet);
        prefEditor.commit();

    }
}
